//
//  Link.m
//  Pble
//
//  Created by 曾 言伟 on 15/10/4.
//  Copyright © 2015年 曾 言伟. All rights reserved.
//

#import "Link.h"

@interface Link ()
{
    CBPeripheral* conper;
    CBCharacteristic *chat;
}
@property (weak, nonatomic) IBOutlet UITableView *sertable;
@property (weak, nonatomic) IBOutlet UILabel *readvalue;

@end

@implementation Link
@synthesize md;

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    [self addNavigatorTitle:NSLocalizedString(md.Peripheral.name, nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        [self dismissViewControllerAnimated:YES completion:nil];
        //[self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"断开" normal:@"" selected:@"" action:^{
        [self disConnect];
    }];
    self.sertable.delegate = self;
    self.sertable.dataSource = self;
    self.navigationItem.title = md.Peripheral.name;
    [self performSelector:@selector(connect) withObject:nil afterDelay:1.0];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(diderror:) name:@"diderror" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"diderror" object:nil];
    
}

-(void) connect
{
    [[X6_bt_a getInstance] ConnectBraceletp:md.Peripheral blk:^(CBPeripheral* per) {
        conper = per;
        [self.sertable reloadData];
    }err:^(NSError* error){
        
    }];
}

- (void) diderror:(NSNotification *) notification
{
    NSString* res = (NSString*)notification.object;
    if([res intValue] == 1)
    {
        [self myAlertView:@"连接失败" delegate:self type:0 tit:@"BLE"];
    }
    else if([res intValue] == 2)
    {
        [self myAlertView:@"已断开" delegate:self type:0 tit:@"BLE"];
    }
}

- (void)myAlertView:(NSString*)str delegate:(id)delegate type:(int)t tit:(NSString*) tit
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tit message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        //code
        
    }];
    [alertController addAction:okAction];
    [delegate presentViewController:alertController animated:YES completion:nil];
}
//- (IBAction)disConnect:(UIButton *)sender {
- (void)disConnect{
    if(conper == nil)
        return;
    [[X6_bt_a getInstance] DisconnectBraceletp:conper blk:^(BOOL val){
        conper = nil;
        
        //[self delayHUD:@"蓝牙设备断开了"];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"蓝牙设备断开了" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [self dismissViewControllerAnimated:YES completion:nil];
        //[self performSelectorOnMainThread:@selector(goBack) withObject:nil waitUntilDone:YES];
        
    }err:^(NSError* error){
        
    }];
}

//-(void) goBack{
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [conper.services count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [((CBService *)[conper.services objectAtIndex:section]).characteristics count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"%@",((CBService *)[conper.services objectAtIndex:section]).UUID];
}

-(const char *) CBUUIDToString:(CBUUID *) UUID {
    return [[UUID.data description] cStringUsingEncoding:NSStringEncodingConversionAllowLossy];
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cellr";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    //cell.textLabel.text = [NSString stringWithFormat:@"%s",[self CBUUIDToString:((CBCharacteristic *)[((CBService *)[conper.services objectAtIndex:indexPath.section]).characteristics objectAtIndex:indexPath.row]).UUID]];
    CBCharacteristic *chat0 = (CBCharacteristic *)[((CBService *)[conper.services objectAtIndex:indexPath.section]).characteristics objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %s",chat0.UUID,[self CBUUIDToString:chat0.UUID]];
    cell.detailTextLabel.text = [self getProperties:chat0.properties];
    return cell;
}

-(NSString*) getProperties:(CBCharacteristicProperties) pro
{
    NSMutableString* spro = [[NSMutableString alloc] init];
    
    if((pro & 0x200) == 0x200)
        [spro appendString:@"IndicateEncryptionRequired"];
    if((pro & 0x100) == 0x100)
        [spro appendString:@"NotifyEncryptionRequired  "];
    if((pro & 0x80) == 0x80)
        [spro appendString:@"ExtendedProperties  "];
    if((pro & 0x40) == 0x40)
        [spro appendString:@"AuthenticatedSignedWrites  "];
    if((pro & 0x20) == 0x20)
        [spro appendString:@"Indicate  "];
    if((pro & 0x10) == 0x10)
        [spro appendString:@"Notify  "];
    if((pro & 0x08) == 0x08)
        [spro appendString:@"Write  "];
    if((pro & 0x04) == 0x04)
        [spro appendString:@"WriteWithoutResponse  "];
    if((pro & 0x02) == 0x02)
        [spro appendString:@"Read  "];
    if((pro & 0x01) == 0x01)
        [spro appendString:@"Broadcast"];
    return spro;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    chat = (CBCharacteristic *)[((CBService *)[conper.services objectAtIndex:indexPath.section]).characteristics objectAtIndex:indexPath.row];
    md.chat0 = chat;
    if((chat.properties & 0x02) == 0x02)
    {
        [[X6_bt_a getInstance] ReadDataBlock:conper chart:chat blk:^(NSString* value){
            self.readvalue.text = [NSString stringWithFormat:@"Read/Notify %@",value];
        }err:^(NSError* error){
            
        }];
    }
    
    if((chat.properties & 0x10) == 0x10)
    {
        [[X6_bt_a getInstance] SetNotiyf:conper chart:chat blk:^(BOOL val){
            if(val)
                [self myAlertView:@"SetNotiyf 成功" delegate:self type:0 tit:@"BLE"];
            else
                [self myAlertView:@"SetNotiyf 失败" delegate:self type:0 tit:@"BLE"];
        }err:^(NSError* error)
         {
             
         }];
        [[X6_bt_a getInstance] ReadDataBlock:conper chart:chat blk:^(NSString* value){
            
        }err:^(NSError* error){
            
        }];
    }
    if((chat.properties & 0x04) == 0x04)//WriteWithoutResponse
    {
        [self performSegueWithIdentifier:@"del" sender:md];
        
    }
    if((chat.properties & 0x08) == 0x08)//0x08
    {
        [self performSegueWithIdentifier:@"del" sender:md];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    UIViewController *destination = segue.destinationViewController;
    [destination setValue:md forKey:@"md"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
